package com.abocode.smarten.client.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;

/**
 * Description:
 * Define a  {@code ConnectionHandler} extends {@link ChannelInboundHandlerAdapter}.
 *
 * @author: guanxianfei
 * @date: 2019/7/24
 */
public class ConnectionHandler extends ChannelInboundHandlerAdapter {

    private String clientMsg;
    private final Charset charset;

    public ConnectionHandler(String clientMsg) {
        charset = Charset.forName("UTF-8");
        this.clientMsg = clientMsg;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String msg = clientMsg + "\r\n";
        ByteBuf encoded = Unpooled.copiedBuffer(msg, charset);
        ctx.channel().writeAndFlush(encoded);
    }
}
